Prompt conditions

You may use handlebars-like branching logic in prompt:

{{#if variable == "value1"}}
prompt-element-1
{{#elseif variable == "value2"}}
prompt-element-2
{{#else}}
prompt-element-3
{{/if}}

The prompt expansion happens BEFORE the prompt is sent to LLM. Therefore, the LLM doesn’t see any branching logic, but only the remaining prompt elements.

Conditions syntax

A condition is an expression that evaluates to true or false. For the complete list of operators and functions you can use – comparison, logical, arithmetic and array operators, string methods, type casting, len() and more – see Expression syntax.

Inside a condition, refer to variables by name, “as is” – without curly brackets. The {{ }} belongs to the #if tag itself, not to the variables inside it. For example, in {{#if age > 18}} the variable is written as age, not {age}.

A few common examples:

You may also nest #if / #elseif constructs to create more complex branching.

Prompt expansion process

It is important to understand that prompt expansion and conditions evaluation happen before the prompt is sent to the LLM. The following examples illustrate this concept.

Example 1

For prompt:

{{#if role == "admin"}}
User has full access to the system.
{{#elseif role == "user"}}
User has limited access to the system.
{{#else}}
User is not allowed to access to the system.
{{/if}}

Assuming that the role variable is set to admin, LLM will receive the following: User has full access to the system.

Example 2

For prompt:

{{#if user_age > 18 and subscription_status == "active"}}
User has access to premium content
{{#else}
User doesn't have access to premium content.
{{/if}}

Assuming that the user_age variable is set 16, LLM will receive the following: User doesn't have access to premium content.

Example 3

For prompt:

Hello {{#if gender == "male"}}Mr{{#else}}Mrs{{/if}} Smith!

Assuming that the gender variable is set male, LLM will receive the following: Hello Mr Smith!

Use of time variables in conditions

If you want to use time variables in #if / #elseif conditions, you must place quotes around the curly brackets.

For example:

Say good {{#if "{current_time}" < "10:00"}} morning {{#else}} day {{/if}}

Rationale for this special syntax is that time variables expansion happens first and only after it is done, the conditions are evaluated. Therefore, by the time condition evaluation logic runs, {current_time} is already replaced with corresponding value, for example, 09:43:00, which needs to be enclosed in double quotes for valid condition statement.